package ltd.dujiabao.mavenLocalInstaller.util;

import java.io.File;
import java.util.Objects;

import ltd.dujiabao.mavenLocalInstaller.jar.JarReader;
import ltd.dujiabao.mavenLocalInstaller.domain.PomProperties;

/**
 * @author : DuJiabao
 * @Project : mavenLocalInstaller
 * @Time : 2021/9/29 0:39
 * @Desc :
 */
public class MavenUtils {
    /**
     * 根据pom.properties的信息，获取jar包在maven仓库的相对路径
     *
     * @return 相对路径，例子：com\fasterxml\jackson\datatype\jackson-datatype-jdk8\2.11.4
     */
    public static String getRelativeDirInRepository(PomProperties pomProperties) {
        String groupId = pomProperties.getGroupId().replace(".", File.separator);
        String artifactId = pomProperties.getArtifactId();
        String version = pomProperties.getVersion();
        return groupId + File.separator + artifactId + File.separator + version;
    }

    /**
     * 通过cmd命令 获取本地maven仓库地址
     *
     * @return maven 仓库地址，有可能会返回null值。
     * 例子: D:\apache-maven-3.6.3\maven-repo\
     */
    public static String getLocalRepositoryPath() {
        // 发送获取本地仓库的命令
        String localRepositoryPath = CmdUtils.exec("mvn help:evaluate -Dexpression=settings.localRepository | find /v \"[INFO]\"");
        // 如果查出来了，那就简单处理一下再返回
        if (!StringUtils.isEmpty(localRepositoryPath)) {
            localRepositoryPath = localRepositoryPath.split("\n")[0];
            localRepositoryPath = PathUtils.ensureEndWithSeparator(localRepositoryPath);
            return localRepositoryPath;
        }
        return null;
    }

    /**
     * 本地安装jar包，提供绝对路径即可
     * @param filePath 文件绝对路径
     * @return
     */
    public static String installJarLocally(String filePath) {
        PomProperties pomProperties = JarReader.getPomProperties(filePath);
        if (Objects.isNull(pomProperties)) {
            System.out.println(filePath + " contains no pom.properties");
            return null;
        }
        return installJarLocally(filePath, pomProperties);
    }

    /**
     * 本地安装jar包，提供绝对路径即可
     * @param filePath 文件绝对路径
     * @param pomProperties pom.properties文件的对象
     * @return
     */
    public static String installJarLocally(String filePath, PomProperties pomProperties) {
        String cmd = "mvn install:install-file " +
                " -DgroupId=" + pomProperties.getGroupId() +
                " -DartifactId=" + pomProperties.getArtifactId() +
                " -Dversion=" + pomProperties.getVersion() +
                " -Dpackaging=jar " +
                " -Dfile=" + filePath;
        return CmdUtils.exec(cmd);
    }

    public static void main(String[] args) {
        System.out.println(installJarLocally("E:\\tools\\mavenLocalInstaller\\temp\\jackson-annotations-2.11.4.jar"));
    }

}
